/*
 * sensor_bus.c
 *
 * Created: 8/16/2011 3:35:38 PM
 *  Author: t-kagu
 */ 
#include <asf.h>

bool twi_bus_init(uint32_t bus_speed)
{
	twi_bus_t * const twi = &AVR32_TWI;
	//
	// Specify TWI master bus configuration options.
	//
	twi_options_t twi_options = { .speed = bus_speed, .chip = 0 };
	//
	// Initialize the Atmel Software Framework TWI master driver.
	//
	return (STATUS_OK == twi_master_setup (twi, &twi_options));
}

/*! \internal Read bytes from remote device using TWI (master) interface
 *
 * This routine reads "count" Bytes of data into location "data" from
 * a specified TWI "bus_id" device register or memory address, "addr".
 *
 * The caller must ensure that "data" specifies a valid memory address
 * that is capable of storing the specified "count" Bytes of data.
 *
 * \param   bus     An initialized bus interface descriptor.
 * \param   addr    The device register or memory address.
 * \param   data    The destination read buffer address.
 * \param   count   The destination read buffer size (Bytes).
 *
 * \return The number of Bytes read, which may be less than the
 *         requested number of Bytes in the event of an error.
 */
size_t twi_bus_read
( uint8_t chip, uint8_t addr, void *data, size_t count)
{
	status
	twi_package_t const pkg = {
		.chip        = chip,
		.addr        = addr,
		.addr_length = sizeof(addr),
		.buffer      = data,
		.length      = count };

	bus->status = twi_master_read(&AVR32_TWI, &pkg);
	return (STATUS_OK == bus->status) ? count : 0;
}

/*! \internal Write bytes to remote device using TWI (master) interface
 *
 * This routine writes "count" Bytes of data from location "data" to
 * a specified TWI "bus_id" device register or memory address, "addr".
 *
 * The caller must ensure that "data" specifies a valid memory address.
 *
 * \param   bus     An initialized bus interface descriptor.
 * \param   addr    The device register or memory address.
 * \param   data    The source write buffer address.
 * \param   count   The source write buffer size (Bytes).
 *
 * \return The number of Bytes written, which may be less than the
 *         requested number of Bytes in the event of an error.
 */
size_t twi_bus_write (bus_desc_t *bus, uint8_t addr, const void *data, 
	size_t count)
{
	twi_package_t const pkg = {
		.chip        = bus->addr,
		.addr        = addr,
		.addr_length = sizeof(addr),
		.buffer      = (void *) data,
		.length      = count };

	bus->status = twi_master_write(bus->id, &pkg);
	return (STATUS_OK == bus->status) ? count : 0;
}